package org.jeecg.modules.demo.ch.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.demo.ch.Utils.OrderBomUtils;
import org.jeecg.modules.demo.ch.common.BigDecimalUtil;
import org.jeecg.modules.demo.ch.common.CommonMst;
import org.jeecg.modules.demo.ch.entity.ChCustomerPositions;
import org.jeecg.modules.demo.ch.entity.ChHub;
import org.jeecg.modules.demo.ch.entity.XcbzT;
import org.jeecg.modules.demo.ch.exception.Assert;
import org.jeecg.modules.demo.ch.exception.CustomException;
import org.jeecg.modules.demo.ch.service.IChCustomerPositionsService;
import org.jeecg.modules.demo.ch.service.IChHubService;
import org.jeecg.modules.demo.ch.service.IXcbzTService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: HUB仓数据
 * @Author: jeecg-boot
 * @Date: 2022-10-12
 * @Version: V1.0
 */
@Api(tags = "HUB仓数据")
@RestController
@RequestMapping("/ch/chHub")
@Slf4j
public class ChHubController extends JeecgController<ChHub, IChHubService> {
    @Autowired
    private IChHubService chHubService;

    @Autowired
    private IXcbzTService iXcbzTService; //Hub仓取数据  从T100的axcq210作业

    @Autowired
    private IChCustomerPositionsService iChCustomerPositionsService; //导入客户需求数


    /**
     * 导入HUB仓数
     *
     * @param chHub
     * @return
     */
    //@AutoLog(value = "HUB仓数据")
    @ApiOperation(value = "导入HUB仓数", notes = "导入HUB仓数")
    @GetMapping(value = "/exportHubList")
//    @Transactional(rollbackFor = Exception.class)
    public Result<IPage<ChHub>> exportHubList(ChHub chHub) throws CustomException {
        long startTime = System.currentTimeMillis();
        //参数校验
        Assert.validateEntity(chHub);
        chHub.setInat009(OrderBomUtils.setStringIfNotNull(OrderBomUtils.setIntegerIfNotNull(chHub.getInat009())));//期别转数字
        //1.参数赋值
        String xcbzcomp = chHub.getInatsite();//据点
        String XCBZ001 = chHub.getInat008();//年度
        String XCBZ006 = chHub.getInat004();//HUB仓代码
        String XCBZ002 = chHub.getInat009();//期别

        //2.根据参数进行查询.
        List<XcbzT> xcbzTList = iXcbzTService.queryList(xcbzcomp, XCBZ001, XCBZ006, XCBZ002);
        if (CollectionUtils.isEmpty(xcbzTList)) {
            return Result.error("根据条件查询无数据!");
        }
        ArrayList<ChHub> chHubArrayList = toConvert(xcbzTList, iXcbzTService);
        log.info("访问时间为：" + (System.currentTimeMillis() - startTime));
        //4.本地保存一份最新数据 方便后续逻辑处理
        chHubService.remove(new QueryWrapper<>());
        chHubService.saveBatch(chHubArrayList);
        log.info("访问时间为：" + (System.currentTimeMillis() - startTime));
        return Result.ok("环境准备成功！");
    }

    /**
     * 分页列表查询
     *
     * @param chHub
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "HUB仓数据-分页列表查询")
    @ApiOperation(value = "导入HUB仓数-分页列表查询", notes = "导入HUB仓数-分页列表查询")
    @GetMapping(value = "/list")
//    @Transactional(rollbackFor = Exception.class)
    public Result<IPage<ChHub>> queryPageList(ChHub chHub, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) throws CustomException {
        //QueryWrapper<ChHub> queryWrapper = QueryGenerator.initQueryWrapper(chHub, req.getParameterMap());
        //参数校验
        Assert.validateEntity(chHub);
        chHub.setInat009(OrderBomUtils.setStringIfNotNull(OrderBomUtils.setIntegerIfNotNull(chHub.getInat009())));//期别转数字
        //5.分页查询本地库 返回结果集
        String inat001 = chHub.getInat001();//料件编号
        if (StringUtils.hasLength(inat001)) {
            inat001 = inat001.trim();
        }
        String inat003 = chHub.getInat003();//库存管理特征
        if (StringUtils.hasLength(inat003)) {
            inat003 = inat003.trim();
        }
        String inat006 = chHub.getInat006();//批号
        if (StringUtils.hasLength(inat006)) {
            inat006 = inat006.trim();
        }


        LambdaQueryWrapper<ChHub> chHubLambdaQueryWrapper = new QueryWrapper<ChHub>().lambda();
        chHubLambdaQueryWrapper.eq(ChHub::getInatsite, chHub.getInatsite());//据点
        chHubLambdaQueryWrapper.eq(ChHub::getInat008, chHub.getInat008());//年度
        chHubLambdaQueryWrapper.eq(ChHub::getInat004, chHub.getInat004());//HUB仓代码
        chHubLambdaQueryWrapper.eq(ChHub::getInat009, chHub.getInat009());//期别
        chHubLambdaQueryWrapper.like(StringUtils.hasLength(inat001), ChHub::getInat001, inat001);//料件编号
        chHubLambdaQueryWrapper.like(StringUtils.hasLength(inat003), ChHub::getInat003, inat003);//库存管理特征
        chHubLambdaQueryWrapper.like(StringUtils.hasLength(inat006), ChHub::getInat006, inat006);//批号
        chHubLambdaQueryWrapper.orderByAsc(ChHub::getInat001);//根据料号进行升序排序
        chHubLambdaQueryWrapper.orderByDesc(ChHub::getInat006);//根据批号进行降序排序
        Page<ChHub> page = new Page<>(pageNo, pageSize);
        IPage<ChHub> iPage = chHubService.page(page, chHubLambdaQueryWrapper);
        if (CollectionUtils.isEmpty(iPage.getRecords())) {
            return Result.error("查询无数据,请核查查询参数!");
        }
        return Result.ok(iPage);
    }

    /**
     * list转换
     *
     * @param xcbzTList
     * @param iXcbzTService
     * @return
     */
    public static ArrayList<ChHub> toConvert(List<XcbzT> xcbzTList, IXcbzTService iXcbzTService) {
        ArrayList<ChHub> chHubArrayList = new ArrayList<>();
        for (XcbzT record : xcbzTList) {
            ChHub chHub1 = new ChHub();
            chHub1.setInatsite(OrderBomUtils.setStringIfNotNull(record.getXcbzld()));//据点（xcbzld）
            chHub1.setInat001(OrderBomUtils.setStringIfNotNull(record.getXcbz003()));//料件编号（cmt_xcbz003）
            chHub1.setInat003(OrderBomUtils.setStringIfNotNull(record.getXcbz005()));//库存管理特征（cmt_xcbz005）
            chHub1.setInat004(OrderBomUtils.setStringIfNotNull(record.getXcbz006()));//HUB仓代码（cmt_xcbz006）
            chHub1.setInat006(OrderBomUtils.setStringIfNotNull(record.getXcbz008()));//批号（cmt_xcbz008）
            chHub1.setInat007(OrderBomUtils.setStringIfNotNull(record.getXcbz009()));//单位（cmt_xcbz009）
            chHub1.setInat008(OrderBomUtils.setStringIfNotNull(record.getXcbz001()));//年度(cmt_Xcbz001)
            chHub1.setInat009(OrderBomUtils.setStringIfNotNull(record.getXcbz002()));//期别(cmt_xcbz002)

            //3.1根据料号查询最新的价格
            if (StringUtils.hasLength(chHub1.getInat001())) {
                String price = iXcbzTService.queryPriceByNo(chHub1.getInat001());
                chHub1.setInat010(OrderBomUtils.supplementZero(price));//单价
            }
            chHub1.setInat015(OrderBomUtils.setStringIfNotNull(record.getXcbz901()));//期末结存数量（cmt_xcbz901）
            chHub1.setInat016(OrderBomUtils.setStringIfNotNull(record.getXcbz201()));//本期入库的数量（cmt_xcbz201）
            chHub1.setCustomerQty("");//客户数量
            chHub1.setCurrentQty("");//当前数量
            chHub1.setRemainder("");//结余数量
            chHubArrayList.add(chHub1);
        }
        return chHubArrayList;
    }

    /**
     * 添加
     *
     * @param chHub
     * @return
     */
    @AutoLog(value = "HUB仓数据-添加")
    @ApiOperation(value = "HUB仓数据-添加", notes = "HUB仓数据-添加")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_hub:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ChHub chHub) {
        chHubService.save(chHub);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param chHub
     * @return
     */
    @AutoLog(value = "HUB仓数据-编辑")
    @ApiOperation(value = "HUB仓数据-编辑", notes = "HUB仓数据-编辑")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_hub:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ChHub chHub) {
        chHubService.updateById(chHub);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "HUB仓数据-通过id删除")
    @ApiOperation(value = "HUB仓数据-通过id删除", notes = "HUB仓数据-通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_hub:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        chHubService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "HUB仓数据-批量删除")
    @ApiOperation(value = "HUB仓数据-批量删除", notes = "HUB仓数据-批量删除")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_hub:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.chHubService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "HUB仓数据-通过id查询")
    @ApiOperation(value = "HUB仓数据-通过id查询", notes = "HUB仓数据-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ChHub> queryById(@RequestParam(name = "id", required = true) String id) {
        ChHub chHub = chHubService.getById(id);
        if (chHub == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(chHub);
    }

//    /**
//     * 导出excel
//     *
//     * @param request
//     * @param chHub
//     */
//    //@RequiresPermissions("org.jeecg.modules.demo:ch_hub:exportXls")
//    @RequestMapping(value = "/exportXls")
//    public ModelAndView exportXls(HttpServletRequest request, ChHub chHub) {
//        return super.exportXls(request, chHub, ChHub.class, "HUB仓数据");
//    }

//    /**
//     * 导出excel
//     */
//    @RequestMapping(value = "/exportXls")
//    public ModelAndView exportXls() {
//        //1.获取年度 根据HUB和客户需求数两个表的料件编码进行去重合并，并跟据编码进行从小到大进行排序
//        List<String> inat001List = chHubService.queryInat001List();
//        //获取数据库的年度.月度.
//        QueryWrapper<ChHub> queryWrapper = new QueryWrapper<>();
//        queryWrapper.select("DISTINCT inat008,inat009");
//        List<ChHub> list = chHubService.list(queryWrapper);
//        if (CollectionUtils.isEmpty(inat001List) || CollectionUtils.isEmpty(list)) {
//            return new ModelAndView(new JeecgEntityExcelView());
//        }
//        String inat008 = list.get(0).getInat008();//年度
//        String inat009 = list.get(0).getInat009();//月度
//        //2.组装要导出的数据
//        List<ChHub> chHubs= assembleChHub(inat008, inat009, inat001List);
//        // Step.1 组装查询条件查询数据
//        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//
//        // Step.4 AutoPoi 导出Excel
//        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
//        mv.addObject(NormalExcelConstants.FILE_NAME, "Hub导出excel");
//        mv.addObject(NormalExcelConstants.CLASS, ChDesignBomMasterPage.class);
//        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("Hub导出excel", "导出人:" + sysUser.getRealname(), "Hub导出excel"));
//        mv.addObject(NormalExcelConstants.DATA_LIST, chHubs);
//        return mv;
//    }


    /**
     * Ob
     * 导出excel
     *
     * @param request
     */
    //@RequiresPermissions("org.jeecg.modules.demo:ch_design_bom:exportXls")
    @RequestMapping(value = "/exportXls")
    public void exportXls(HttpServletRequest request, HttpServletResponse response) {

        try {

//            //1.获取年度 根据HUB和客户需求数两个表的料件编码进行去重合并，并跟据编码进行从小到大进行排序
//            List<String> inat001List = chHubService.queryInat001List();
//            //获取数据库的年度.月度.
//            QueryWrapper<ChHub> queryWrapper = new QueryWrapper<>();
//            queryWrapper.select("DISTINCT inat008,inat009");
//            List<ChHub> list = chHubService.list(queryWrapper);
//            if (CollectionUtils.isEmpty(inat001List) || CollectionUtils.isEmpty(list)) {
//                return;
//            }
//            String inat008 = list.get(0).getInat008();//年度
//            String inat009 = list.get(0).getInat009();//月度
//            //2.组装要导出的数据
//            List<ChHub> rows = assembleChHub(inat008, inat009, inat001List);

            //需要导出的数据
            List<ChHub> rows = chHubService.list();

            // 通过工具类创建writer
            // createFile(new File(templatePath));
            ExcelWriter writer = ExcelUtil.getWriter(true);
            //自定义标题别名
            writer.addHeaderAlias("inatsite", "据点");
            writer.addHeaderAlias("inat001", "料件编号");
            writer.addHeaderAlias("inat003", "库存管理特征");
            writer.addHeaderAlias("inat004", "HUB仓代码");
            writer.addHeaderAlias("inat006", "批号");
            writer.addHeaderAlias("inat007", "单位");
            writer.addHeaderAlias("inat008", "年度");
            writer.addHeaderAlias("inat009", "期别");
            writer.addHeaderAlias("inat010", "单价");
            writer.addHeaderAlias("inat015", "期末结存数量");
            writer.addHeaderAlias("inat016", "本期入库的数量");
            writer.addHeaderAlias("customerQty", "客户数量");
            writer.addHeaderAlias("currentQty", "当前数量");
            writer.addHeaderAlias("remainder", "结余数量");


            writer.setColumnWidth(-1, 16); // 设置统一列宽20
            // writer.autoSizeColumnAll(); // 设置自动宽度

            // 默认的，未添加alias的属性也会写出，如果想只写出加了别名的字段，可以调用此方法排除之
            writer.setOnlyAlias(true);

//            //跳过当前行，既第一行，非必须，在此演示用
//            writer.passCurrentRow();
//            writer.passCurrentRow();
//            writer.passCurrentRow();
            // 合并单元格后的标题行，使用默认标题样式
//            writer.merge(7, "益模系统的BOM导入模版");
            // 一次性写出内容，使用默认样式，强制输出标题
            writer.write(rows, true);

            StyleSet style = writer.getStyleSet(); //获取整个Excel的样式
            style.setBorder(BorderStyle.THIN, IndexedColors.BLACK1);
            style.setAlign(HorizontalAlignment.CENTER, VerticalAlignment.CENTER); //水平居中，垂直居中

            DataFormat dataFormat = writer.getWorkbook().createDataFormat();
            // number type
            CellStyle numberCellStyle = style.getCellStyleForNumber(); //获取单元格的数值样式
            numberCellStyle.setDataFormat(dataFormat.getFormat("0.0")); //设置为1位小数样式
            for (int i = 1; i < rows.size() + 1; i++) {
                writer.setStyle(numberCellStyle, 1, i); // 设置单元格的样式
                writer.setStyle(numberCellStyle, 2, i); // 设置单元格的样式
                writer.setStyle(numberCellStyle, 3, i); // 设置单元格的样式
                writer.setStyle(numberCellStyle, 4, i); // 设置单元格的样式
                writer.setStyle(numberCellStyle, 5, i); // 设置单元格的样式
                writer.setStyle(numberCellStyle, 6, i); // 设置单元格的样式
                writer.setStyle(numberCellStyle, 7, i); // 设置单元格的样式
                writer.setStyle(numberCellStyle, 8, i); // 设置单元格的样式
            }


            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=test.xlsx");
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out, true);
            writer.close();
            IoUtil.close(out);
        } catch (Exception e) {
            log.error("文件导出异常!", e);
            // return Result.error("文件导出异常!",e);
        }
    }


//    /**
//     * 导出Excel-胡玉洋-2015年11月11日
//     *
//     *@param outPutParam Excel数据实体，包括要导出的excel标头、列标题、数据等
//     * */
//    private void createContentRows(ExcelParam outPutParam) {
//        HSSFWorkbook workbook=new HSSFWorkbook(); //创建一个Excel文件
//        // 遍历集合数据，产生数据行
//        for (int i = 0; i < outPutParam.getContent().size(); i++) {
//            int rowIndex = i + 2;
//            HSSFRow contentRow = sheet.createRow(rowIndex);
//            Map<String, Object> rowDate = outPutParam.getContent().get(i);
//            //遍历列
//            for (int j = 0; j < outPutParam.getTitleList().size(); j++) {
//                Title headTitle = outPutParam.getTitleList().get(j);//获取第i行第j列列标题
//                String headerName = headTitle.getName();//获取第j列列标识
//                Object data = rowDate.get(headerName);//获取第i行第j列所放数据
//                HSSFCellStyle contextstyle =workbook.createCellStyle();
//                HSSFCell contentCell = contentRow.createCell(j);
//                Boolean isNum = false;//data是否为数值型
//                Boolean isInteger=false;//data是否为整数
//                Boolean isPercent=false;//data是否为百分数
//                if (data != null || "".equals(data)) {
//                    //判断data是否为数值型
//                    isNum = data.toString().matches("^(-?\\d+)(\\.\\d+)?$");
//                    //判断data是否为整数（小数部分是否为0）
//                    isInteger=data.toString().matches("^[-\\+]?[\\d]*$");
//                    //判断data是否为百分数（是否包含“%”）
//                    isPercent=data.toString().contains("%");
//                }
//
//                //如果单元格内容是数值类型，涉及到金钱（金额、本、利），则设置cell的类型为数值型，设置data的类型为数值类型
//                if (isNum && !isPercent) {
//                    HSSFDataFormat df = workbook.createDataFormat(); // 此处设置数据格式
//                    if (isInteger) {
//                        contextstyle.setDataFormat(df.getBuiltinFormat("#,#0"));//数据格式只显示整数
//                    }else{
//                        contextstyle.setDataFormat(df.getBuiltinFormat("#,##0.00"));//保留两位小数点
//                    }
//                    // 设置单元格格式
//                    contentCell.setCellStyle(contextstyle);
//                    // 设置单元格内容为double类型
//                    contentCell.setCellValue(Double.parseDouble(data.toString()));
//                } else {
//                    contentCell.setCellStyle(contextstyle);
//                    // 设置单元格内容为字符型
//                    contentCell.setCellValue(data.toString());
//                }
//            }
//        }
//    }


    /**
     * 根据三种情况  组装返回要导出的新集合
     *
     * @param inat008
     * @param inat009
     * @param inat001List
     * @return
     */
    public List<ChHub> assembleChHub(String inat008, String inat009, List<String> inat001List) {
        List<ChHub> chHubList = new ArrayList<>();
        //2.1遍历该合并后的料件编码
        for (String inat001 : inat001List) {
            ChHub chHub = new ChHub(); //组装要导出的实体.
            //第一种情况  根据料件编码和年度和月度 如果该料件编码在Hub仓存数据查不到   根据料号客户需求表数查的到
            //inat015,CustomerQty,CurrentQty等于客户需求数中的CustomerQty  Remainder=0
            List<ChHub> chHubs = hubIsFindByInat001(inat001, inat008, inat009, chHubService);
            List<ChCustomerPositions> chCustomerPositions = chCustomerPositionsIsFindByInat001(inat001, iChCustomerPositionsService);
            if (CollectionUtils.isEmpty(chHubs) && !CollectionUtils.isEmpty(chCustomerPositions)) {
                QueryWrapper<XcbzT> xcbzTQueryWrapper = new QueryWrapper<>();
                xcbzTQueryWrapper.eq("XCBZ001", inat008);
                xcbzTQueryWrapper.eq("XCBZCOMP", CommonMst.HUB.XCBZ_COMP);
                xcbzTQueryWrapper.eq("XCBZ003", inat001);
                xcbzTQueryWrapper.eq("ROWNUM", 1);
                List<XcbzT> xcbzTList = iXcbzTService.list(xcbzTQueryWrapper);
                if (CollectionUtils.isEmpty(xcbzTList)) {
                    log.error("根据年度{},据点{},料号{}未在T100找到该条数据", inat008, CommonMst.HUB.XCBZ_COMP, inat001);
                } else {
                    chHub.setInatsite(OrderBomUtils.setStringIfNotNull(xcbzTList.get(0).getXcbzcomp()));//据点（XCBZCOMP）
                    chHub.setInat001(OrderBomUtils.setStringIfNotNull(xcbzTList.get(0).getXcbz003()));//料件编号
                    chHub.setInat003(OrderBomUtils.setStringIfNotNull(xcbzTList.get(0).getXcbz005()));//库存管理特征
                    chHub.setInat004(OrderBomUtils.setStringIfNotNull(xcbzTList.get(0).getXcbz006()));//HUB仓代码
                    chHub.setInat006(OrderBomUtils.setStringIfNotNull(xcbzTList.get(0).getXcbz008()));//批号
                    chHub.setInat007(OrderBomUtils.setStringIfNotNull(xcbzTList.get(0).getXcbz009()));//单位
                    chHub.setInat008(OrderBomUtils.setStringIfNotNull(xcbzTList.get(0).getXcbz001()));//年度
                    chHub.setInat009(OrderBomUtils.setStringIfNotNull(xcbzTList.get(0).getXcbz002()));//月度
                    chHub.setInat010("");//单价
                    chHub.setInat015(OrderBomUtils.setStringIfNotNull(chCustomerPositions.get(0).getCustomerQty()));//期末结存数量
                    chHub.setCustomerQty(OrderBomUtils.setStringIfNotNull(chCustomerPositions.get(0).getCustomerQty()));//客户数量
                    chHub.setCurrentQty(OrderBomUtils.setStringIfNotNull(chCustomerPositions.get(0).getCustomerQty()));//当前数量
                    chHub.setRemainder(CommonMst.HUB.ZERO);//结余数量
                }
                //第二种情况根据料件编码和年度 如果该料件编码在Hub仓存数据查到 客户需求数也查的到
                //-就取对应的值 	不过其中inat015的值等于Hub中的inat015+客户需求数中的CustomerQty
                //-CustomerQty等于Hub中的CustomerQty  CurrentQty等于客户需求数中的CustomerQty
                //-Remainder的值为最新的inat015-CurrentQty的值
            } else if (!CollectionUtils.isEmpty(chHubs) && !CollectionUtils.isEmpty(chCustomerPositions)) {
                chHub = chHubs.get(0);
                chHub.setInat015(String.valueOf(BigDecimalUtil.add(chHub.getInat015(), OrderBomUtils.setStringIfNotNull(chCustomerPositions.get(0).getCustomerQty()))));
                chHub.setCustomerQty(OrderBomUtils.setStringIfNotNull(chHub.getCustomerQty()));
                chHub.setCurrentQty(OrderBomUtils.setStringIfNotNull(chCustomerPositions.get(0).getCustomerQty()));
                chHub.setRemainder(String.valueOf(BigDecimalUtil.subtract(chHub.getInat015(), chHub.getCurrentQty())));
                //第三种情况
                // -根据料件编码和年度 如果该料件编码在Hub仓存数据查到 客户需求数查不到
                // -直接将Hub仓的数据导出
            } else if (!CollectionUtils.isEmpty(chHubs) && CollectionUtils.isEmpty(chCustomerPositions)) {
                chHub = chHubs.get(0);
            }
            chHubList.add(chHub);
        }
        return chHubList;
    }

    ;

    /**
     * 根据料号 年度  月度 判断是否在Hub找的到
     *
     * @param inat001
     * @param inat008
     * @param inat009
     * @return
     */
    public List<ChHub> hubIsFindByInat001(String inat001, String inat008, String inat009, IChHubService chHubService) {
        LambdaQueryWrapper<ChHub> chHubLambdaQueryWrapper = new QueryWrapper<ChHub>().lambda();
        chHubLambdaQueryWrapper.eq(ChHub::getInat001, inat001);
        chHubLambdaQueryWrapper.eq(ChHub::getInat008, inat008);
        chHubLambdaQueryWrapper.eq(ChHub::getInat009, inat009);
        return chHubService.list(chHubLambdaQueryWrapper);
    }

    /**
     * 根据料号 判断是否在ChCustomerPositions找的到
     *
     * @param inat001
     * @return
     */
    public List<ChCustomerPositions> chCustomerPositionsIsFindByInat001(String inat001, IChCustomerPositionsService iChCustomerPositionsService) {
        LambdaQueryWrapper<ChCustomerPositions> chCustomerPositionsLambdaQueryWrapper = new QueryWrapper<ChCustomerPositions>().lambda();
        chCustomerPositionsLambdaQueryWrapper.eq(ChCustomerPositions::getXmdm001, inat001);
        return iChCustomerPositionsService.list(chCustomerPositionsLambdaQueryWrapper);
    }


    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("ch_hub:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ChHub.class);
//        return super.importExcel2(request,response,ChHub.class);
    }

    /**
     * 数据匹配
     *
     * @return
     */
    //@AutoLog(value = "数据匹配")
    @ApiOperation(value = "数据匹配", notes = "数据匹配")
    @GetMapping(value = "/dataMatching")
    public Result<ChHub> dataMatching() throws CustomException {
        //1.针对客户仓数、针对客户需求数批量更新
        //针对客户仓数
        updateBatchForChHub(chHubService, iChCustomerPositionsService);
        // 针对客户需求数
        updateBatchForChCustomerPositions(chHubService, iChCustomerPositionsService);
        return Result.OK("数据匹配成功！");
    }

    /**
     * 针对客户需求数 批量更新
     *
     * @param chHubService
     * @param iChCustomerPositionsService
     */
    public void updateBatchForChCustomerPositions(IChHubService chHubService, IChCustomerPositionsService iChCustomerPositionsService) {
        List<ChCustomerPositions> chCustomerPositionList = iChCustomerPositionsService.list();
        //客户需求数根据料件编号从Hub仓存数匹配 找不到MatchQty为空  Mstatus为空
        if (!CollectionUtils.isEmpty(chCustomerPositionList)) {
            for (ChCustomerPositions chCustomerPositions : chCustomerPositionList) {
                LambdaQueryWrapper<ChHub> chHubLambdaQueryWrapper1 = new QueryWrapper<ChHub>().lambda();
                chHubLambdaQueryWrapper1.eq(ChHub::getInat001, chCustomerPositions.getXmdm001());
                List<ChHub> chHubs = chHubService.list(chHubLambdaQueryWrapper1);
                if (CollectionUtils.isEmpty(chHubs)) {//为空
                    chCustomerPositions.setMatchQty(null);
                    chCustomerPositions.setCusStatus("");
                } else {//找的到
                    //MatchQty与 Hub仓存数据的CurrentQty一致  如果CustomerQty与MatchQty不同 Mstatus为F  相同为T
                    chCustomerPositions.setMatchQty(OrderBomUtils.setIntegerIfNotNull(chHubs.get(0).getCurrentQty()));
                    if (chCustomerPositions.getCustomerQty() == chCustomerPositions.getMatchQty()) {
                        chCustomerPositions.setCusStatus(CommonMst.HUB.T);
                    } else {
                        chCustomerPositions.setCusStatus(CommonMst.HUB.F);
                    }
                }
            }
            //批量更新
            iChCustomerPositionsService.saveOrUpdateBatch(chCustomerPositionList);
        }
    }

    /**
     * 针对用户仓数批量更新
     *
     * @param chHubService
     * @param iChCustomerPositionsService
     */
    public void updateBatchForChHub(IChHubService chHubService, IChCustomerPositionsService iChCustomerPositionsService) {
        //以客户需求数为准  在T100中找到应该分配的数量
        List<ChCustomerPositions> chCustomerPositions = iChCustomerPositionsService.list();
        if (CollectionUtils.isEmpty(chCustomerPositions)) {
            throw new RuntimeException("导入的客户需求数为空");
        }
        //逻辑匹配
        ArrayList<String> inat001List = new ArrayList<>(); //存放从T100中未查到的料件编号
        List<ChHub> chHubList = new ArrayList<>();//存放更新后的chHublist
        for (ChCustomerPositions chCustomerPositions1 : chCustomerPositions) {
            String xmdm001 = chCustomerPositions1.getXmdm001();//料件编号
            Integer customerQty = chCustomerPositions1.getCustomerQty();//客户需求数
            if (customerQty == null) {
                customerQty = 0;
            }
            LambdaQueryWrapper<ChHub> hubLambdaQueryWrapper = new QueryWrapper<ChHub>().lambda().eq(ChHub::getInat001, xmdm001).orderByDesc(ChHub::getInat006);//按照批次的降序排序  3在前 1在后
            List<ChHub> list1 = chHubService.list(hubLambdaQueryWrapper);
            if (CollectionUtils.isEmpty(list1)) {
                inat001List.add(xmdm001);
                continue;
            }
            //处理单个料号查询的数据
            //private String customerQty;//客户数量
            //private String currentQty; //当前数量
            //private String remainder; //结余数量
            // 还差的数量 num
            double num = 0; //num是正数
            for (ChHub chHub : list1) {
                String inat006 = chHub.getInat006();//批号
                String inat015 = chHub.getInat015();//上期结存数量
                String inat016 = chHub.getInat016();//本期入库数量
                double totalRemainingQuantity = BigDecimalUtil.add(inat015, inat016);//总剩余数量
                chHub.setCustomerQty(String.valueOf(customerQty));//客户数量
                double subtract = BigDecimalUtil.subtract(String.valueOf(totalRemainingQuantity), String.valueOf(customerQty));
                if (inat006.equals(CommonMst.HUB.BATCH_3)) {//处理批次号有3的情况
                    if (subtract > 0) {
                        chHub.setCurrentQty(String.valueOf(customerQty));//当前数量
                        chHub.setRemainder(String.valueOf(subtract));//结余数量
                        num=subtract;
                    } else if (subtract == 0) {
                        chHub.setCurrentQty(String.valueOf(customerQty));//当前数量
                        chHub.setRemainder(CommonMst.HUB.ZERO);//结余数量
                    } else {
                        chHub.setCurrentQty(String.valueOf(totalRemainingQuantity));//当前数量
                        chHub.setRemainder(CommonMst.HUB.ZERO);//结余数量
                        num = subtract;
                    }
                }
                if (inat006.equals(CommonMst.HUB.BATCH_1) || inat006.equals(CommonMst.HUB.BATCH_9005)) {//有批次都为1和90005
                    if (num == 0) {//还差的数量为0
                        chHub.setRemainder(String.valueOf(subtract));//结余数量
                        if (totalRemainingQuantity > customerQty){
                            chHub.setCurrentQty(String.valueOf(customerQty));//当前数量
                        }else {
                            chHub.setCurrentQty(String.valueOf(totalRemainingQuantity));//当前数量
                        }
                    } else if (num >0){
                        //不用进行分配批次为1的情况
                        chHub.setRemainder(String.valueOf(totalRemainingQuantity));//结余数量
                        chHub.setCurrentQty(CommonMst.HUB.ZERO);//当前数量
                    } else {//先分配批次为3后分配批次为1的情况
                        num = -num;
                        subtract = BigDecimalUtil.subtract(String.valueOf(totalRemainingQuantity), String.valueOf(num));
                        chHub.setRemainder(String.valueOf(subtract));//结余数量
                        if (totalRemainingQuantity > num){
                            chHub.setCurrentQty(String.valueOf(num));//当前数量
                        }else {
                            chHub.setCurrentQty(String.valueOf(totalRemainingQuantity));//当前数量
                        }
                    }
                }
                chHubList.add(chHub);
            }
        }
        //删除原来的数据
        chHubService.remove(new QueryWrapper<>());
        //重新新增
        chHubService.saveBatch(chHubList);
        log.info("根据导入的客户需求数未在T100找到的料号有：inat001List：{}", Arrays.asList(inat001List));
    }
}
